import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:vxima/app_book_model.dart';
import 'package:vxima/app_plays_model.dart';
import 'package:vxima/book_playlist_entity.dart';
import 'package:vxima/book_result_entity.dart';
import 'package:vxima/db_utils.dart';
import 'package:vxima/get_data.dart';

void main() {
  runApp(MyApp());
  if (Platform.isAndroid) {
    SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
        statusBarColor: Colors.transparent, //设置为透明
        statusBarIconBrightness: Brightness.dark //light:黑色图标 dark：白色图标
        );
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      // home: MyHomePage(title: 'Listen'),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  AudioPlayer audioPlayer;
  var _areaList = List<AppBookModel>();
  var _localList = List<AppBookModel>();
  var page = 1;
  var readPage = 1;
  var title = "我的";
  var audioName = "****";
  var playerState = AudioPlayerState.STOPPED;
  Duration _duration;
  Duration _position;

  get _durationText => _duration?.toString()?.split('.')?.first ?? '';

  get _positionText => _position?.toString()?.split('.')?.first ?? '';

  @override
  void initState() {
    super.initState();
    audioPlayer = AudioPlayer();
    audioPlayer.onDurationChanged.listen((duration) {
      setState(() {
        _duration = duration;
      });
    });
    audioPlayer.onPlayerCompletion.listen((event) {
      print('event->onPlayerCompletion');
    });
    audioPlayer.onPlayerStateChanged.listen((event) {
      setState(() {
        playerState = event;
      });
    });
    audioPlayer.onAudioPositionChanged.listen((event) {
      setState(() {
        _position = event;
      });
    });
    getDbPlayList().then((value) => {
          if (value.length > 0)
            {
              _localList.addAll(
                  value.map((e) => new AppBookModel.fromJson(e)).toList()),
              _updateText("我的")
            }
        });
  }

  void _updateAudioName(String text) {
    setState(() {
      // update the text
      audioName = text;
    });
  }

  void _updateText(String text) {
    if (text == "搜书" && _areaList.isEmpty) {
      get(1);
    }
    setState(() {
      // update the text
      title = text;
    });
  }

  _getContentView() {
    if (title == "我的") {
      return ListView.builder(
          shrinkWrap: true,
          itemCount: _localList.length,
          itemBuilder: (BuildContext context, int position) {
            return _renderRow(context, position, 2);
          });
    } else if (title == "搜书") {
      return SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: MaterialClassicHeader(),
        footer: ClassicFooter(),
        controller: _refreshController,
        onRefresh: () {
          page = 1;
          get(page);
        },
        onLoading: (){
          page++;
          get(page);
        },
        child: new ListView.builder(
            shrinkWrap: true,
            itemCount: _areaList.length,
            itemBuilder: (BuildContext context, int position) {
              return _renderRow(context, position, 1);
            }),
      );
    } else if (title == "正在播放") {
      return Container(
        child: Column(
          children: [
            Container(
              height: 40,
              child: Center(
                child: Text(
                  audioName,
                ),
              ),
            ),
            const Divider(thickness: 1),
            Column(
              children: <Widget>[
                Slider(
                  onChanged: (v) {
                    final Position = v * _duration.inMilliseconds;
                    audioPlayer.seek(Duration(milliseconds: Position.round()));
                  },
                  value: (_position != null &&
                          _duration != null &&
                          _position.inMilliseconds > 0 &&
                          _position.inMilliseconds < _duration.inMilliseconds)
                      ? _position.inMilliseconds / _duration.inMilliseconds
                      : 0.0,
                ),
                Text(
                  _position != null
                      ? '${_positionText ?? ''} / ${_durationText ?? ''}'
                      : _duration != null ? _durationText : '',
                  style: TextStyle(fontSize: 24.0),
                ),
                RaisedButton(
                  child: Text("${(readPage - 1) * 50 + 1}-${readPage * 50}"),
                  onPressed: () {
                    setState(() {
                      readPage = 2;
                    });
                  },
                ),
                GridView.builder(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 10,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10,
                    ),
                    itemCount: 50,
                    shrinkWrap: true,
                    itemBuilder: (BuildContext context, int index) {
                      return Container(
                        alignment: Alignment.center,
                        child: Text(
                          "${index + 1}",
                          style: TextStyle(color: Colors.white),
                        ),
                        color: Colors.lightBlueAccent,
                      );
                    })
              ],
            ),
          ],
        ),
      );
    } else {
      return Container(
        alignment: Alignment.center,
        child: Text("data"),
      );
    }
  }

  _getPlayIcon() {
    if (playerState == AudioPlayerState.PLAYING) {
      return Icon(Icons.pause);
    } else {
      return Icon(Icons.play_arrow);
    }
  }

  play(String url) async {
    int result = await audioPlayer.play(url);
    if (result == 1) {
      // success
      print('aaa->play success');
    } else {
      print('aaa->play failed');
    }
  }

  get(int page) async {
    try {
      List<AppBookModel> list = await getBooksResult(page);
      setState(() {
        if (page == 1) {
          _areaList.clear();
        }
        _areaList.addAll(list);
      });
    } catch (e) {}
    if (page == 1) {
      _refreshController.refreshCompleted();
    } else {
      _refreshController.loadComplete();
    }
  }

  getList(int id, int page) async {
    try {
      List<AppPlaysModel> list = await getPlayList(id, page);
      _updateAudioName(list[0].title);
      play(list[0].playlink);
    } catch (e) {
      print(e);
    }
  }

  Widget _renderRow(BuildContext context, int index, int type) {
    List mList;
    if (type == 1) {
      mList = _areaList;
    } else if (type == 2) {
      mList = _localList;
    }
    return ListTile(
      leading: CircleAvatar(
        backgroundImage:
            NetworkImage("http://imagev2.xmcdn.com/${mList[index].cover}"),
      ),
      title: Text(mList[index].title),
      subtitle: Text(mList[index].customTitle),
      onTap: () {
        // play(_areaList[index].split('____')[3]);
        if (type == 1) {
          Scaffold.of(context).showBottomSheet(
              // (context) => _BottomSheetContent(_areaList[index]));
              (context) => Container(
                    child: Column(
                      children: [
                        Container(
                          height: 40,
                          child: Center(
                            child: Text(
                              _areaList[index].title,
                            ),
                          ),
                        ),
                        const Divider(thickness: 1),
                        Column(
                          children: <Widget>[
                            Text(_areaList[index].bookdesc),
                            const Divider(thickness: 1),
                            Text(_areaList[index].authorname),
                            const Divider(thickness: 1),
                            Text("  "),
                            Text("  "),
                            Text("  "),
                            RaisedButton(
                              child: Text("加入书架"),
                              onPressed: () {
                                bool bc = false;
                                _localList.forEach((element) {
                                  if (element.iId == _areaList[index].iId) {
                                    bc = true;
                                  }
                                });
                                if (bc) {
                                  return;
                                }
                                var bean = _areaList[index];
                                _localList.add(bean);
                                addToPlayList(
                                    bean.iId,
                                    bean.cover,
                                    bean.title,
                                    bean.customTitle,
                                    bean.bookdesc,
                                    bean.authorname);
                                setState(() {
                                  _updateText("我的");
                                });
                                Navigator.of(context).pop();
                              },
                            ),
                          ],
                        ),
                      ],
                    ),
                  ));
        } else if (type == 2) {
          print("ids->" + _localList[index].iId.toString());
          getList(_localList[index].iId, _localList[index].num);
          // play("");
        }
      },
    );
  }

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawerEdgeDragWidth: 0.0,
      appBar: AppBar(
        title: Text(title),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            Container(
              color: Colors.blueAccent,
              alignment: Alignment.center,
              height: 156,
              child: ClipOval(
                child: Image.asset(
                  "image/head.jpg",
                  height: 96,
                  width: 96,
                ),
              ),
            ),
            ListTile(
              leading: Icon(Icons.account_circle),
              title: Text("我的"),
              onTap: () => {_updateText("我的"), Navigator.of(context).pop()},
            ),
            Divider(),
            ListTile(
              leading: Icon(Icons.search),
              title: Text("搜书"),
              onTap: () => {_updateText("搜书"), Navigator.of(context).pop()},
            ),
            Divider(),
            ListTile(
              leading: Icon(Icons.settings_applications),
              title: Text("设置"),
              onTap: () => {_updateText("设置"), Navigator.of(context).pop()},
            ),
          ],
        ),
      ),
      body: Scaffold(
          body: new Column(
        children: <Widget>[
          Expanded(flex: 1, child: _getContentView()),
          Container(
            color: Color(0xFFF2F2F2),
            width: double.infinity,
            height: 56,
            child: Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: Builder(builder: (BuildContext context) {
                      return Container(
                        child: GestureDetector(
                          child: Text(
                            audioName,
                            maxLines: 1,
                            style: TextStyle(fontSize: 18.0),
                          ),
                          onTap: () {
                            setState(() {
                              _updateText("正在播放");
                            });
                          },
                        ),
                        margin: const EdgeInsets.only(left: 5),
                      );
                    })),
                IconButton(
                  icon: _getPlayIcon(),
                  onPressed: () {
                    if (playerState == AudioPlayerState.PLAYING) {
                      audioPlayer.pause();
                    } else if (playerState == AudioPlayerState.PAUSED) {
                      audioPlayer.resume();
                    }
                  },
                ),
              ],
            ),
          ),
        ],
      )),
    );
  }
}
